<template>
  <VTable ref="tableRef" v-bind="tableOptins">
    <template #form="{ form }">
      <XForm :fieldList="fieldList" :formOption="optionsData" :formData="form">
        <template #user="{ value, input }">
          <VCascader
            :model-value="value"
            @update:model-value="input"
            collapse-tags
            style="width: 200px"
            placeholder="创建人"
          />
        </template>
        <template #queryNo="{ input, value }">
          <VBatchInput
            @update:model-value="input"
            :model-value="value"
            placeholder="请输入"
            class="w-60"
            @search="refresh"
          />
        </template>
      </XForm>
    </template>
    <template #toolbar_btns>
      <VActionBar :actions="actions" />
    </template>
    <template #declare_file="{ row }">
      <VLink :file="row?.prediction_files?.declare_files || []" />
    </template>
    <template #tc_number="{ row }">
      <template v-for="(i, idx) in row?.tc_number || []" :key="i">
        <div v-if="idx < 1">{{ i }}</div>
      </template>
      <div class="text-left">
        <el-text
          type="primary"
          class="cursor-pointer text-[#3487FF]"
          v-if="row.tc_number.length > 1"
          @click="
            tcNumberLogRef?.open({
              data: row.tc_number,
              title: '头程备库单号',
            })
          "
          >更多信息</el-text
        >
      </div>
    </template>
    <template #shipment_id="{ row }">
      <template v-for="(i, ind) in row?.shipment_id || []" :key="i">
        <div v-if="ind < 1">{{ i }}</div>
      </template>
      <div class="text-left">
        <el-text
          type="primary"
          class="cursor-pointer text-[#3487FF]"
          v-if="row.shipment_id.length > 1"
          @click="
            tcNumberLogRef?.open({
              data: row.shipment_id,
              title: 'ShipmentID海外仓入库单号',
            })
          "
          >更多信息</el-text
        >
      </div>
    </template>
    <template #pre_no="{ row }">
      <el-link type="primary">
        <router-link
          :to="`/export-rebates/forecast-list/details?id=${row?.id}`"
          >{{ row?.pre_no }}</router-link
        >
      </el-link>
    </template>
    <template #dm_status="{ row }">
      <span
        class="align-middle"
        :class="row?.dm_status == '正常' ? 'text-[#333]' : 'text-[#e50113]'"
        >{{ row?.dm_status }}</span
      >
      <el-button
        v-if="row?.dm_status"
        link
        :type="row?.dm_status == '正常' ? 'primary' : 'danger'"
        @click="handleStatus(row)"
      >
        {{ "详情>>" }}
      </el-button>
    </template>
    <template #operation="{ row }">
      <div class="flex items-center">
        <el-button
          link
          type="primary"
          @Click="handleDetail(row.id)"
          v-hasPermi="[exportRebatesAuthList.forecast_list.details]"
        >
          查看
        </el-button>
        <el-button
          v-if="[0, 2]?.includes(row?.audit_status)"
          link
          type="primary"
          @Click="handleEdit(row)"
          v-hasPermi="[exportRebatesAuthList.forecast_list.edit]"
        >
          编辑
        </el-button>
        <el-dropdown
          @command="
            ($event) => {
              handleCommand($event, row);
            }
          "
        >
          <SvgIcon class="ml-[16px]" icon-class="more" />
          <template #dropdown>
            <el-dropdown-menu v-matomo>
              <el-dropdown-item
                v-for="(item, index) in operateList"
                :key="index"
                :disabled="
                  !item?.isShow?.includes(row?.audit_status) ||
                  !isPermission(item.permission)
                "
                :command="item.label"
                >{{ item?.label }}</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </template>
  </VTable>
  <tcNumberLog ref="tcNumberLogRef" />
  <dmStatus v-model="statusVisible" :data="statusData" />
  <Log
    dialog
    v-model="logVisible"
    :autoLoad="false"
    tag="out.prediction"
    :business_id="logId"
    @close="logId = null"
  />
  <ConfirmInput
    :title="auditTitle"
    class="w-[500px]"
    confirmButtonText="确认"
    v-model="approvalVisible"
    :loading="loading"
    :field-options="approvalOptions"
    :rules="approvalRules"
    @submit="handleApprovalReq"
  />
  <customsImportDialog
    v-model="customsImportVisible"
    @refresh="refresh"
    :title="customsTitle"
    @close="customsId = ''"
    :id="customsId"
  />
  <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  <importDialog ref="importDialogRef" @refresh="refresh" />
  <supervisionDialog
    v-model="supervisionVisible"
    @refresh="refresh"
    :data="supervisionData"
    :options="optionsData['out_regulatory_approach']"
    @close="supervisionData = {}"
  />
</template>
<script setup lang="jsx">
import { ElMessage } from "element-plus";
import tcNumberLog from "../tcNumberLog/index.vue";
import dmStatus from "../dmStatus/index.vue";
import XForm from "@/components/XForm/index.vue";
import VLink from "@/components/VLink/index.vue";
import SvgIcon from "@/components/SvgIcon/index.vue";
import { exportRebatesAuthList } from "@/Auth/export-rebates.js";
import { isPermission } from "@/hooks/permission.js";
import { handleLink, tipMessage } from "@/hooks/tool.js";
import Log from "@/components/Log/index.vue";
import DerivedCenter from "@/components/DerivedCenter/index.vue";
import ConfirmInput from "@/components/ConfirmInput/index.vue";
import { getTableSelectRow, getTableSelect } from "@/hooks/tool.js";
import importDialog from "@/components/importDialog/index.vue";
import supervisionDialog from "../supervisionDialog/index";
import {
  predictionList,
  predictionSubmit,
  predictionCancel,
  predictionAudit,
  predictionFs,
  predictionDmDetails,
  predictionDownload,
  predictionDpFile,
  predictionFinanceAudit,
} from "../../api/index.js";
import { config_name } from "@/config/export.js";
import customsImportDialog from "../customsImportDialog/index.vue";
import VBatchInput from '@/componentsPublic/BatchInput/index.vue'
const { proxy } = getCurrentInstance();
const router = useRouter();
const props = defineProps({
  optionsData: { type: Object, default: () => {} },
});
const { optionsData } = toRefs(props);
const tableRef = ref();
const tcNumberLogRef = ref();
const tableOptins = reactive({
  formConfig: {
    data: {
      dateRange: { type: "declare_date", value: [], range: false }, // 组合+日期范围
    },
  },
  tooltipConfig: {
    showAll: false,
  },
  rowClassName({ row }) {
    if (row.audit_status === 5) {
      return "row-danger";
    }
    return null;
  },
  rowConfig: { height: 130 },
  isToggle: true,
  columns: [
    { fixed: "left", width: 50, type: "checkbox" },
    {
      fixed: "left",
      title: "头程备库单号",
      minWidth: 220,
      field: "tc_number",
      slots: { default: "tc_number" },
    },
    {
      title: "ShipmentID海外仓入库单号",
      width: 220,
      field: "shipment_id",
      slots: { default: "shipment_id" },
    },
    {
      title: "合同号",
      width: 150,
      field: "contract_number",
    },
    {
      title: "物流商",
      width: 240,
      field: "logistics_name",
    },

    { title: "境内发货人", width: 200, field: "domestic_consignors" },
    { title: "境外收货人", width: 160, field: "offshore_consignee" },
    { title: "预报状态", width: 160, field: "audit_status_label" },
    { title: "报关备注", minWidth: 260, field: "declare_remark" },
    { title: "出口日期", width: 170, field: "out_date" },
    { title: "申报时间", width: 170, field: "declare_date" },
    { title: "申报人员", width: 170, field: "declare_user" },
    {
      width: 160,
      title: "预报单号",
      field: "pre_no",
      slots: { default: "pre_no" },
    },
    {
      title: "数据匹配状态",
      width: 160,
      field: "dm_status",
      slots: { default: "dm_status" },
    },
    {
      title: "审核人员",
      width: 160,
      field: "audit_user",
    },
    { title: "审核时间", width: 200, field: "audit_time" },
    { title: "报关单号", width: 160, field: "declare_number" },
    {
      title: "报关文件",
      width: 260,
      field: "",
      slots: { default: "declare_file" },
    },
    { title: "预报文件下载次数", width: 160, field: "pre_file_download_nums" },
    { title: "驳回备注", width: 160, field: "audit_remark" },
    {
      title: "操作",
      width: 150,
      field: "",
      fixed: "right",
      slots: { default: "operation" },
    },
  ],
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page, form }) => {
        return predictionList({ ...form, ...page }).then((res) => {
          return {
            data: res.data,
            total: res.total,
          };
        });
      },
    },
  },
});
//数据匹配状态
const statusVisible = ref(false);
const statusData = ref({});
const handleStatus = async (row) => {
  let data = await getDetail({ id: row?.id });
  statusVisible.value = true;
  statusData.value = data;
};

const getDetail = async (id) => {
  const res = await predictionDmDetails({ id });
  if (res.code !== 200) {
    ElMessage.warning(res.message);
    return;
  }
  return res?.data || {};
};
//详情
const handleDetail = (id) => {
  router.push(`/export-rebates/forecast-list/details?id=${id}`);
};
//编辑
const handleEdit = (row) => {
  router.push(`/export-rebates/forecast-list/add?id=${row.id}`);
};
//提交
const confirmationDialog = ({ msg, api, ids }) => {
  proxy?.confirm({
    title: "提示",
    content: <p> {msg} </p>,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message } = await api({
            id: ids,
          });
          if (code !== 200) {
            ElMessage.warning(message);
            return;
          }
          ElMessage.success(`${msg}成功!`);
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};
const confirmationDialogMore = ({ msg, api, ids }) => {
  proxy?.confirm({
    title: "提示",
    content: <p> {msg} </p>,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          const { code, message, data } = await api({
            id: ids,
          });
          if (code !== 200) {
            ElMessage.warning(message);
            return;
          }
          tipMessage(data);
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};
//提交
const handleSubmit = (item) => {
  confirmationDialogMore({
    msg: "确认提交该条数据？",
    api: predictionSubmit,
    ids: item.id,
  });
};
//作废
const handleCancel = (item) => {
  confirmationDialogMore({
    msg: "确认作废该条数据？",
    api: predictionCancel,
    ids: item.id,
  });
};
// const handleLog = () => {};
//下载预报文件
const handleForecast = async (row) => {
  try {
    const res = await predictionDpFile({ id: row?.id, do: "download" });
    if (res.code !== 200) {
      ElMessage.warning(res.message);
      return;
    }
    handleLink(res.data.oss_path);
  } catch (error) {}
};
const customsId = ref("");
const handleUpCustoms = (row) => {
  customsImportVisible.value = true;
  customsTitle.value = "上传匹配报关信息";
  customsId.value = row?.id;
};
//下载报关文件
const handleCustoms = async (row) => {
  try {
    let res = await predictionDownload({ id: row?.id, do: "download" });
    if (res.code !== 200) {
      ElMessage.warning(res.message);
      return;
    }
    handleLink(res.data.oss_path);
  } catch (error) {}
};
const handleUnAudit = (item) => {
  confirmationDialogMore({
    msg: "是否反审到待提交状态",
    api: predictionFs,
    ids: item.id,
  });
};

//反审
const approvalOptions = [
  {
    label: "审核状态",
    field: "audit",
    type: "radio",
    style: { width: "100%" },
    options: {
      data: [
        { label: "通过", value: "pass" },
        { label: "驳回", value: "rejected" },
      ],
    },
    itemProps: {
      popperAppendToBody: true,
      teleported: true,
    },
  },
  {
    label: "驳回原因",
    field: "remark",
    type: "textarea",
    style: { marginTop: "10px" },
    autosize: { minRows: 4, maxRows: 8 },
    show: ({ model }) => model.audit === "rejected",
  },
];
const approvalRules = {
  audit: [{ required: true, message: "请选择审核状态", trigger: "blur" }],
};
const auditTitle = ref("");
const approvalVisible = ref(false);
const loading = ref(false);
const auditData = ref({});
const handleAudit = (item) => {
  approvalVisible.value = true;
  auditData.value = item;
  auditTitle.value = item?.flage;
};
const handleApprovalReq = async (formValues) => {
  const { id, flage } = auditData.value;
  const _api = {
    复审: predictionAudit,
    财务审核: predictionFinanceAudit,
  };
  const obj = {
    id,
    ...formValues,
  };
  try {
    loading.value = true;
    const { code, message, data } = await _api[flage](obj);
    if (code !== 200) {
      ElMessage.warning(message);
      return;
    }
    tipMessage(data);
    auditData.value = null;
    approvalVisible.value = false;
    refresh();
  } catch (e) {
  } finally {
    loading.value = false;
  }
};

//修改监管方式
const supervisionVisible = ref(false);
const supervisionData = ref({});
const handleSupervision = (item) => {
  supervisionVisible.value = true;
  supervisionData.value = {
    id: item.id,
    regulatory_approach: item.regulatory_approach,
    contract_number: item.contract_number,
  };
};

// //日志
const logVisible = ref(false);
const logId = ref(null);
const handleLog = (row) => {
  logId.value = row?.id;
  logVisible.value = true;
};

//导出中心
const DerivedCenterRef = ref();
const handleExport = async () => {
  let condition = getTableSelectRow(tableRef.value);
  DerivedCenterRef.value.open({
    tag_name: config_name["export_rebates"]["prediction"],
    condition,
  });
};
const handleExportShop = async () => {
  let condition = getTableSelectRow(tableRef.value);
  DerivedCenterRef.value.open({
    tag_name: config_name["export_rebates"]["export_out_prediction_skus"],
    condition,
  });
};
const handleCommand = (e, row) => {
  const _item = operateList.find((n) => n.label === e);
  _item?.fn?.(JSON.parse(JSON.stringify(Object.assign({}, row, { flage: e }))));
};

//上传匹配报关信息
const importDialogRef = ref();
const handleExportInfo = () => {
  importDialogRef.value?.open({
    type: "out.predictionDmDetails",
    urlType: "/out/prediction/import-dm-details",
  });
};
//批量下载预报文件
const handleDpFile = () => {
  // let id = tableRef.value?.$table.getCheckboxRecords();
  let id = getTableSelect(tableRef.value);
  if (!id?.length) return ElMessage.warning("请至少选择一条数据!");
  proxy?.confirm({
    title: "提示",
    content: `确认下载${id.length}条数据？`,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";

          const fn = async (list) => {
            return new Promise(async (resolve, reject) => {
              const res = await predictionDpFile({
                id: list[0],
                do: "download",
              });
              if (res.code !== 200) {
                resolve();
              }
              handleLink(res.data.oss_path);
              list.shift();
              if (list?.length) {
                setTimeout(() => {
                  resolve(fn(list));
                }, 500);
              } else {
                resolve();
              }
            });
          };
          await fn(id);

          ElMessage.warning(message);
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          refresh();
        }
      } else {
        done();
      }
    },
  });
};
const batchSubmit = () => {
  // let id = tableRef.value?.$table.getCheckboxRecords();
  let id = getTableSelect(tableRef.value);
  if (!id?.length) return ElMessage.warning("请至少选择一条数据!");
  confirmationDialogMore({
    msg: `确认提交${id.length}条数据？`,
    api: predictionSubmit,
    ids: id,
  });
};
const handleAuditFs = () => {
  // let id = tableRef.value?.$table.getCheckboxRecords();
  let id = getTableSelect(tableRef.value);
  if (!id?.length) return ElMessage.warning("请至少选择一条数据!");
  confirmationDialogMore({
    msg: "是否反审到待提交状态",
    api: predictionFs,
    ids: id,
  });
};
const batchAudit = () => {
  // let id = tableRef.value?.$table.getCheckboxRecords();
  let id = getTableSelect(tableRef.value);
  if (!id?.length) return ElMessage.warning("请至少选择一条数据!");
  handleAudit({ flage: "复审", id });
};
const batchFinanceAudit = () => {
  let id = getTableSelect(tableRef.value);
  if (!id?.length) return ElMessage.warning("请至少选择一条数据!");
  handleAudit({ flage: "财务审核", id });
};
const handleFinanceAudit = (item) => {
  handleAudit({ flage: "财务审核", id: item?.id });
};
const batchCancel = () => {
  // let id = tableRef.value?.$table.getCheckboxRecords();
  let id = getTableSelect(tableRef.value);
  if (!id?.length) return ElMessage.warning("请至少选择一条数据!");
  confirmationDialogMore({
    msg: `确认作废${id.length}条数据？`,
    api: predictionCancel,
    ids: id,
  });
};
const customsTitle = ref("");
const customsImportVisible = ref(false);
const handleExportCustoms = () => {
  customsImportVisible.value = true;
  customsTitle.value = "批量上传匹配报关信息";
};
// const handleExport = () => {};

const refresh = () => {
  tableRef?.value.query()
};
const actions = ref([
  {
    label: "批量提交",
    type: "primary",
    fn: batchSubmit,
    permission: [exportRebatesAuthList.forecast_list.submit],
  },
  {
    label: "上传匹配报关信息",
    fn: handleExportInfo,
    permission: [exportRebatesAuthList.forecast_list.import],
  },

  {
    label: "批量下载预报文件",
    fn: handleDpFile,
    permission: [exportRebatesAuthList.forecast_list.downforecastfile],
  },
  {
    label: "批量反审",
    fn: handleAuditFs,
    permission: [exportRebatesAuthList.forecast_list.repeated],
  },
  {
    label: "批量复核",
    fn: batchAudit,
    permission: [exportRebatesAuthList.forecast_list.recheck],
  },

  {
    label: "批量作废功能",
    fn: batchCancel,
    permission: [exportRebatesAuthList.forecast_list.cancel],
  },
  {
    label: "批量上传报关单文件",
    fn: handleExportCustoms,
    permission: [exportRebatesAuthList.forecast_list.upforecastfile],
  },
  {
    label: "批量财务审核",
    fn: batchFinanceAudit,
    permission: [exportRebatesAuthList.forecast_list.finance],
  },
  {
    label: "导出申报信息",
    right: true,
    dkicon: "icon-Upload",
    fn: handleExportShop,
    permission: [exportRebatesAuthList.forecast_list.export],
  },
  {
    label: "导出",
    right: true,
    dkicon: "icon-Upload",
    fn: handleExport,
    permission: [exportRebatesAuthList.forecast_list.export],
  },
]);

const operateList = [
  {
    label: "提交",
    fn: handleSubmit,
    isShow: [0, 2],
    permission: [exportRebatesAuthList.forecast_list.submit],
  },
  {
    label: "作废",
    fn: handleCancel,
    isShow: [0, 2],
    permission: [exportRebatesAuthList.forecast_list.cancel],
  },
  {
    label: "日志",
    fn: handleLog,
    isShow: [0, 1, 2, 3, 4, 5, 6, 7, 8],
    permission: [exportRebatesAuthList.forecast_list.cancel],
  },
  {
    label: "下载预报文件",
    fn: handleForecast,
    isShow: [4],
    permission: [exportRebatesAuthList.forecast_list.downforecastfile],
  },
  {
    label: "上传报关文件",
    fn: handleUpCustoms,
    isShow: [4, 6],
    permission: [exportRebatesAuthList.forecast_list.upforecastfile],
  },
  {
    label: "下载报关文件",
    fn: handleCustoms,
    isShow: [4],
    permission: [exportRebatesAuthList.forecast_list.downcustomsfile],
  },
  {
    label: "反审",
    fn: handleUnAudit,
    isShow: [4, 7],
    permission: [exportRebatesAuthList.forecast_list.downcustomsfile],
  },
  {
    label: "复审",
    fn: handleAudit,
    isShow: [3],
    permission: [exportRebatesAuthList.forecast_list.repeated],
  },
  {
    label: "财务审核",
    fn: handleFinanceAudit,
    isShow: [8],
    permission: [exportRebatesAuthList.forecast_list.finance],
  },
  {
    label: "监管方式",
    fn: handleSupervision,
    isShow: [4],
    permission: [exportRebatesAuthList.forecast_list.repeated],
  },
];

const publicStyle = { style: { width: "240px" } };
const fieldList = [
  {
    field: "numberNo",
    placeholder: "请输入",
    // type: "input",
    select: [
      { label: "预报单号", value: "pre_no" },
      { label: "头程备库单号", value: "tc_number" },
      { label: "报关单号", value: "declare_number" },
      { label: "合同号", value: "contract_number" },
      { label: "亚马逊货件(FBAID)", value: "shipment_id" },
      { label: "配货单号", value: "ph_number" },
    ],
    selectStyle: { width: "130px" },
    slot: "queryNo",
    // itemProps: {
    //   type: "textarea",
    //   autosize: { minRows: 1, maxRows: 2 },
    // },
  },
  {
    field: "logistics_id",
    type: "select",
    originOption: "logistics",
    options: {
      placeholder: "物流商名称",
      labelKey: "logistics_name",
      valueKey: "logistics_id",
    },
    collapseTags: true,
    multiple: true,
    class: "select-wrapper-style",
    ...publicStyle,
  },
  {
    field: "audit_status",
    type: "select",
    originOption: "out_prediction_audit_status",
    options: {
      placeholder: "审核状态",
    },
    style: { width: "140px" },
  },
  {
    field: "warehouse_id",
    type: "select",
    originOption: "warehouse",
    options: {
      placeholder: "发货仓",
    },
    style: { width: "150px" },
  },
  {
    field: "dateRange",
    type: "dateTimeRange",
    style: { width: "360px" },
    selectStyle: { width: "100px" },
    select: [
      { label: "申报时间", value: "declare_date" },
      { label: "审核时间", value: "audit_time" },
    ],
    itemProps: {
      startPlaceholder: "最早时间",
      endPlaceholder: "最晚时间",
    },
  },
  {
    field: "user",
    selectStyle: { width: "100px" },
    select: [{ label: "申报人", value: "declare_user" }],
    options: {
      placeholder: "请选择",
    },
    slot: "user",
  },
  {
    field: "is_upload_declare_file",
    type: "select",
    style: { width: "160px" },
    options: {
      placeholder: "报关单是否上传",
      data: [
        { label: "是", value: 1 },
        { label: "否", value: 0 },
      ],
    },
  },
  {
    field: "is_upload_pass_file",
    type: "select",
    style: { width: "160px" },
    options: {
      placeholder: "放行单是否上传",
      data: [
        { label: "是", value: 1 },
        { label: "否", value: 0 },
      ],
    },
  },
  {
    field: "is_upload_take_file",
    type: "select",
    style: { width: "160px" },
    options: {
      placeholder: "提单是否上传",
      data: [
        { label: "是", value: 1 },
        { label: "否", value: 0 },
      ],
    },
  },
];
</script>
<style lang="scss" scoped>
.vx-table {
  height: calc(100% - 40px) !important;
}
:deep(.vxe-grid .vxe-body--row.row-danger) {
  background-color: var(--base-danger-bg);
}
:deep(.vxe-grid .vxe-body--row.row-danger .cell--fixed) {
  background-color: var(--base-danger-bg);
}
</style>
